package com.zst.bluetooth.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.zst.bluetooth.R;
import com.zst.bluetooth.adapter.DeviceAdapter;
import com.zst.bluetooth.bean.BluetoothMsg;
import com.zst.bluetooth.utils.BlueToothUtils;

import java.util.ArrayList;
import java.util.List;

public class FindActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView statusTv;
    private TextView logTv;
    private Button searchBtn;
    private DeviceAdapter adapter;
    private List<String> devices = new ArrayList<>();
    private BluetoothReceiver bluetoothReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("查找设备");
        initWidget();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        bluetoothReceiver = new BluetoothReceiver();
        registerReceiver(bluetoothReceiver, filter);
    }

    /**
     * 初始化界面
     */
    private void initWidget() {
        RecyclerView deviceRv = (RecyclerView) findViewById(R.id.find_devices);
        statusTv = (TextView) findViewById(R.id.find_status);
        logTv = (TextView) findViewById(R.id.find_log);
        searchBtn = (Button) findViewById(R.id.find_btn);
        adapter = new DeviceAdapter(this, devices);
        adapter.setOnItemClickListener(new DeviceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, String addr, String name) {
                BluetoothMsg.blueToothAddress = addr;//截取蓝牙地址
                if (!(BluetoothMsg.lastBlueToothAddress.equals(BluetoothMsg.blueToothAddress))) {
                    BluetoothMsg.lastBlueToothAddress = BluetoothMsg.blueToothAddress;//将连接的蓝牙地址保存起来
                    BluetoothMsg.blueToothName = name;
                }
                BlueToothUtils.stopFind();
                Intent intent = new Intent(FindActivity.this, MessageActivity.class);
                FindActivity.this.startActivity(intent);
            }
        });
        deviceRv.setAdapter(adapter);
        deviceRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        searchBtn.setOnClickListener(this);
        logTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        logTv.setText("点击[搜索]按钮开始发现蓝牙设备\n");
    }

    @Override
    public void onClick(View v) {
        if (v.equals(searchBtn)) {
            if (!searchBtn.getText().toString().contains("搜索")) {
                searchBtn.setText("重新搜索");
                BlueToothUtils.stopFind();
                logTv.append("用户取消了搜索\n");
            } else {
                searchBtn.setText("停止");
                logTv.append("开始搜索\n");
                devices = BlueToothUtils.find();
                if (devices.size() == 0) {
                    logTv.append("没有已配对的设备\n");
                } else {
                    logTv.append("找到" + devices.size() + "个已配对的设备:\n");
                    for (String d : devices) {
                        logTv.append(d + "\n");
                    }
                }
                adapter.notify(new ArrayList<>(devices));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
    }

    private class BluetoothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //搜索没有配过对的蓝牙设备
                if (btd.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (!devices.contains(btd.getName() + "##" + btd.getAddress())) {
                        devices.add(btd.getName() + "##" + btd.getAddress());
                        logTv.append("查找到新设备:\n");
                        logTv.append(btd.getName() + "##" + btd.getAddress() + "\n");
                        adapter.notify(new ArrayList<>(devices));
                    }
                }
            } else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                searchBtn.setText("重新搜索");
                logTv.append("搜索完成\n=====================\n");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }
}
